import BaseFunction as BF
import MyClass as mc
import time

# Type ;  1:更新 2:获取

# 获取任务队列
def GetMissionList():
    sqlCmd = 'select * from Thread where IsFinish = 0 Order by Priority'
    rows = BF.selectmssql(sqlCmd, None, **BF.sqlparms)
    missionList = []
    if len(rows) == 0:
        print("当前无任务需要执行!")
        return None
    for i in range(0, len(rows)):
        missionList.append(mc.MyThread(rows[i]['ID'], rows[i]['IsFinish'], rows[i]['Priority'],
                                       rows[i]['Type'], rows[i]['Params']))

    return missionList


def Start():
    MissionList = GetMissionList()
    if MissionList is None:
        return None
    for i in range(0, len(MissionList)):
        # 更新
        if MissionList[i].Type == 1:
            # 获取链接
            href = BF.selectmssql("select href from BooksInfo Where BID=%s",
                                  MissionList[i].Params, **BF.sqlparms)[0]['href']
            # 获取最新章节列表
            chapters = BF.check(href)
            # 获取原有章节数
            Num = BF.selectmssql('select Num from UpdateInfo Where BID = %s',
                                 MissionList[i].Params, **BF.sqlparms)[0]['Num']
            if Num < len(chapters):
                zjc = chapters[Num:]
                # 获取正文
                BF.Update(zjc, MissionList[i].Params, href)
                # 存入数据库
                BF.Save(zjc, MissionList[i].Params)
                BF.myssqlUpdate("update UpdateInfo set State=0,IsDispose = 0 Where BID=%s",
                                MissionList[i].Params, **BF.sqlparms)
        if MissionList[i].Type == 2:
            href = BF.selectmssql("select href from BooksInfo Where BID=%s",
                                  MissionList[i].Params, **BF.sqlparms)[0]['href']
            # 获取最新章节列表
            chapters = BF.check(href)
            BF.Update(chapters, MissionList[i].Params, href)
            BF.Save(chapters, MissionList[i].Params)
            BF.myssqlUpdate("update UpdateInfo set State=0,IsDispose = 0 Where BID=%s",
                            MissionList[i].Params, **BF.sqlparms)

        BF.myssqlUpdate("update Thread set IsFinish = 1 where ID=%s", MissionList[i].ID, **BF.sqlparms)


while True:
    time.sleep(5)
    print('获取最新任务列表')
    Start()